<template>
  <a-card class="order-container">
    <!-- 订单状态筛选 -->
    <div class="order-tabs">
      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <a-tab-pane :key="0" tab="全部订单"></a-tab-pane>
        <a-tab-pane :key="1" tab="待付款"></a-tab-pane>
        <a-tab-pane :key="2" tab="待发货"></a-tab-pane>
        <a-tab-pane :key="3" tab="待收货"></a-tab-pane>
        <a-tab-pane :key="4" tab="待评价"></a-tab-pane>
        <a-tab-pane :key="5" tab="已取消"></a-tab-pane>
        <a-tab-pane :key="6" tab="已评价"></a-tab-pane>
      </a-tabs>
    </div>

    <!-- 订单列表 -->
    <div class="order-list" style="height: calc(100vh - 300px); overflow: auto;">
      <a-list item-layout="vertical" size="large" :data-source="orderList" :loading="loading" :pagination="pagination">
        <template #renderItem="{ item }">
          <a-list-item key="item.id">
            <div class="comment" style="height: 60px;display: flex;align-items: center;justify-content: space-between;"
              v-if="activeTab === 6">
              <div style="display: flex;align-items: center;">
                <div style="width: 200px;">
                  <a-avatar>
                    <template #icon>
                      <a-avatar :src="item.user.avatar" />
                    </template>
                  </a-avatar>
                  <span style="padding-left: 10px;">{{ item.user.nickname }}</span>
                </div>
                <div>
                  <a-rate :value="item.rating" disabled />
                  <div>
                    {{ item.content }}
                  </div>
                </div>
              </div>
              <div>
                {{ formatTime(item.createdAt) }}
              </div>
            </div>
            <div style="padding-left: 40px;">
              <!-- 订单头部信息 -->
              <div class="order-header">
                <span class="order-time">{{ formatTime(item.create_time) }}</span>
                <span class="order-number">订单号: {{ item.order_no }}</span>
                <span class="order-status">{{ getStatusText(item.order_status) }}</span>
              </div>

              <!-- 订单商品信息 -->
              <div class="order-goods">
                <a-row :gutter="16">
                  <a-col :span="18">
                    <a-list item-layout="horizontal" :data-source="item.productList">
                      <template #renderItem="{ item: goods }">
                        <a-list-item>
                          <a-list-item-meta>
                            <template #avatar>
                              <a-image :width="80" :height="80" :src="goods.image" :preview="false" />
                            </template>
                            <template #title>
                              <a href="/goods/detail" target="_blank">{{ goods.title }}</a>
                            </template>
                            <template #description>
                              <div class="goods-spec">{{ goods.spec }}</div>
                              <div class="goods-price">¥{{ goods.price.toFixed(2) }}</div>
                            </template>
                          </a-list-item-meta>
                          <div class="goods-quantity">x{{ goods.quantity }}</div>
                        </a-list-item>
                      </template>
                    </a-list>
                  </a-col>
                  <a-col :span="6" class="order-summary">
                    <div class="total-amount">
                      实付款：<span class="amount">¥{{ Number(item.order_amount).toFixed(2) }}</span>
                    </div>
                    <div class="action-buttons">
                      <template v-if="item.order_status === 1">
                        <a-button type="primary" @click="handlePay(item)">立即付款</a-button>
                        <a-button @click="handleCancel(item)">取消订单</a-button>
                      </template>
                      <template v-else-if="item.order_status === 2">
                        <a-button @click="handleRemind(item)">提醒发货</a-button>
                      </template>
                      <template v-else-if="item.order_status === 3">
                        <a-button type="primary" @click="handleConfirm(item)">确认收货</a-button>
                      </template>
                      <template v-else-if="item.order_status === 4">
                        <a-button @click="handleRate(item)">立即评价</a-button>
                        <!-- <a-button @click="handleDelete(item)">删除订单</a-button> -->
                      </template>
                    </div>
                  </a-col>
                </a-row>
              </div>
            </div>
          </a-list-item>
        </template>
      </a-list>
    </div>
    <Comment ref="commentRef" />
    <PayModal ref="paymentModal" :amount="totalAmount" @success="handlePaymentSuccess" :show-cancel="false" />
  </a-card>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { getOrder, updateOrder, removeOrder, queryMyReviews } from '@/apis/user/order';
import moment from 'moment';
import PayModal from '@/components/payModal.vue';
import Comment from './comment.vue';
export default {
  components: { PayModal, Comment },
  setup() {
    // 状态管理
    const activeTab = ref(0);
    const loading = ref(false);
    const orderList = ref([]);

    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '20', '30', '50'],
      onChange: (page, pageSize) => {
        pagination.current = page;
        pagination.pageSize = pageSize;
        if (activeTab.value === 6) {
          fetchMyComment();
        } else {
          fetchOrders();
        }
      },
    });

    // 获取订单状态文本
    const getStatusText = (status) => {
      const statusMap = ['全部', '待付款', '待发货', '待收货', '已完成', '已取消'];
      return statusMap[status] || '';
    };

    // 格式化时间
    const formatTime = (time) => {
      return moment(time).format('YYYY-MM-DD HH:mm:ss');
    };

    // 获取订单列表
    const fetchOrders = async () => {
      try {
        loading.value = true;
        const data = {
          order_status: activeTab.value,
          page: pagination.current,
          limit: pagination.pageSize,
        }
        if (!activeTab.value) delete data.order_status;
        // 这里替换为实际的API调用
        const res = await getOrder(data);
        orderList.value = res.data.list.map(item => {
          return {
            ...item,
            productList: JSON.parse(item.product)
          }
        });
        pagination.total = res.data.total;
      } catch (error) {
        message.error('获取订单列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 获取订单列表
    const fetchMyComment = async () => {
      try {
        loading.value = true;
        const data = {
          order_status: activeTab.value,
          page: pagination.current,
          limit: pagination.pageSize,
        }
        if (!activeTab.value) delete data.order_status;
        // 这里替换为实际的API调用
        const res = await queryMyReviews(data);
        orderList.value = res.data.list.map(item => {
          return {
            ...item,
            create_time: item.order.create_time,
            order_amount: item.order.order_amount,
            order_no: item.order.order_no,
            productList: JSON.parse(item.order.product)
          }
        });
        pagination.total = res.data.total;
      } catch (error) {
        message.error('获取评价列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 标签页切换
    const handleTabChange = (key) => {

      activeTab.value = key;
      pagination.current = 1;
      if (key === 6) {
        fetchMyComment();
      } else {
        fetchOrders();
      }
    };
    const paymentModal = ref(null);
    const payForOrderId = ref({})
    const totalAmount = ref(0)
    // 各种操作处理函数
    const handlePay = (order) => {
      message.info(`正在支付订单: ${order.order_no}`);
      payForOrderId.value = order.order_id
      totalAmount.value = Number(order.order_amount);
      // 实际调用支付API
      paymentModal.value.open();
    };

    const handlePaymentSuccess = () => {
      handleOrderStatus(payForOrderId.value, 2)
    }

    const handleCancel = (order) => {
      message.info(`取消订单: ${order.order_no}`);
      // 实际调用取消订单API
      handleOrderStatus(order.order_id, 5)
    };

    const handleRemind = (order) => {
      message.success(`已提醒商家发货: ${order.order_no}`);
      // handleOrderStatus(order.order_id,3)
    };

    const handleConfirm = (order) => {
      message.success(`确认收货: ${order.order_no}`);
      // 实际调用确认收货API
      handleOrderStatus(order.order_id, 4)
    };



    const handleDelete = (order) => {
      removeOrder(order.order_id).then(res => {
        if (res.code === 0) {
          fetchOrders();
          message.success(`删除订单${order.order_no}成功`);
        }
      })
    };

    const handleOrderStatus = (id, status) => {
      updateOrder(id, {
        order_status: status
      }).then((res) => {
        if (res.code === 0) {
          fetchOrders();
        }
      })
    }

    const commentRef = ref();
    const handleRate = (item) => {
      console.log(commentRef.value);

      commentRef.value.open(item.order_id);
    }




    // 初始化加载
    onMounted(() => {
      fetchOrders();
    });

    return {
      commentRef,
      handleRate,
      activeTab,
      loading,
      orderList,
      pagination,
      getStatusText,
      formatTime,
      handleTabChange,
      paymentModal,
      totalAmount,
      handlePay,
      handleCancel,
      handleRemind,
      handleConfirm,
      handleDelete,
      handlePaymentSuccess
    };
  },
};
</script>
<style scoped>
.order-container {
  margin: 20px;
}

.order-tabs {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
}

.order-time {
  color: #999;
}

.order-number {
  margin-left: 20px;
}

.order-status {
  color: #ff5000;
  font-weight: bold;
}

.order-goods {
  padding: 10px 0;
}

.goods-spec {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.goods-price {
  color: #ff5000;
  font-weight: bold;
  margin-top: 5px;
}

.goods-quantity {
  color: #666;
}

.order-summary {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
}

.total-amount {
  font-size: 16px;
}

.amount {
  color: #ff5000;
  font-size: 18px;
  font-weight: bold;
}

.action-buttons {
  margin-top: 15px;
}

.action-buttons button {
  margin-left: 10px;
  margin-bottom: 10px;
}
</style>